<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>计算属性</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<h2>计算属性</h2>
<div id="example">
    <p>原始信息: "{{ message }}"</p>
    <p>反转计算信息: "{{ reveredMessage }}"</p>
</div>
<h2>监听器</h2>
<div id="watch-example">
    <p>
        Ask a yes/no question
        <input v-model="question">
    </p>
    <p>{{ answer }}</p>
</div>
</body>
</html>
<script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/lodash@4.13.1/lodash.min.js"></script>
<script type="application/javascript">
    var vm = new Vue({
        el: '#example',
        data: {
            message: 'Hello Hon  vue'
        },
        computed: {
            reveredMessage:function () {
                return this.message.split('').reverse().join('')
            }
        }
    })


    //监听器
    var watchVm = new Vue({
        el: '#watch-example',
        data: {
            question: '',
            answer: 'I cannot give you an answer until you ask a question!'
        },
        watch: {
            question:function (mewQuestion,oldQuestion) {
                this.answer = 'Waiting for you to stop typing...'
                this.debouncedGetAnswer()
            }
        },
        created: function(){
            this.debouncedgetAnswer = _.debounce(this.getAnswer,500)
        },
        methods: {
            getAnswer: function () {
                if (this.question.indexOf('?') === -1){
                    this.answer = 'Questions usually contain a question mark. :-)'
                    return
                }
                this.answer = 'Thinking...'
                var vm = this
                axios.get('https://yesno.wtf/api')
                    .then(function (response) {
                        vm.answer = _.capitalize(response.data.answer)
                    })
                    .catch(function (error) {
                        vm.answer = 'Error! Could not reach the Api.' + error
                    })
            }
        }
    })
</script>